//
//  HTLoginVC.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/29.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTLoginVC.h"
#import "NSString+RMCExtension.h"

#define kBackBlue  HTColorRGB(180,213,249)

@interface HTLoginVC ()<UITextFieldDelegate>
    @property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
    @property (weak, nonatomic) IBOutlet UITextField *codeStr;
    @property (weak, nonatomic) IBOutlet UIButton *loginBtn;
    @property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
    @property (weak, nonatomic) IBOutlet UILabel *versionLabel;
    @property (assign,nonatomic)int timeout;




@end

@implementation HTLoginVC
    
static dispatch_source_t _timer1;
    
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登陆";
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    self.versionLabel.text  = [NSString stringWithFormat:@"司机版v%@",app_Version];
    [self setBtn];
    [self setUpTextFields];
}
- (void)setBtn {
 
    self.loginBtn.backgroundColor = kBackBlue;
    self.loginBtn.userInteractionEnabled = NO;
    self.getCodeBtn.backgroundColor = kBackBlue;
    self.getCodeBtn.userInteractionEnabled = NO;
}
    //设置文本框的属性
- (void)setUpTextFields{
    self.phoneNumber.delegate = self;
    self.codeStr.delegate = self;
    [self.phoneNumber addTarget:self action:@selector(phoneTextValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.codeStr addTarget:self action:@selector(codeTextValueChanged:) forControlEvents:UIControlEventEditingChanged];
    //手机号文本框格式
    self.phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.codeStr.keyboardType = UIKeyboardTypeNumberPad;
    self.codeStr.clearButtonMode = UITextFieldViewModeWhileEditing;
    
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.phoneNumber) {
        if (textField.text.length >= 11 && string.length > 0) {
            return NO;
        }else{
            return YES;
        }
    }else if(textField == self.codeStr) {
        if (textField.text.length >= 4 && string.length > 0) {
            return NO;
        }else{
            return YES;
        }
        
    }
    return NO;
}
    
//手机文本框文本改变
- (void)phoneTextValueChanged:(UITextField *)sender {
    
    if (sender.text.length < 11) {
        
        self.getCodeBtn.backgroundColor = kBackBlue;
        self.getCodeBtn.userInteractionEnabled = NO;
        self.loginBtn.backgroundColor = kBackBlue;
        self.loginBtn.userInteractionEnabled = NO;
        
    } else if (sender.text.length >= 11) {
        
        self.getCodeBtn.backgroundColor = kBlueColor;
        self.getCodeBtn.userInteractionEnabled = YES;
        if (self.codeStr.text.length > 3) {
            self.loginBtn.backgroundColor = kBlueColor;
            self.loginBtn.userInteractionEnabled = YES;
        }else{
            self.loginBtn.backgroundColor = kBackBlue;
            self.loginBtn.userInteractionEnabled = NO;
        }
        
    }
    
}
    //验证码文本框改变
- (void)codeTextValueChanged:(UITextField *)sender {
    
    if (sender.text.length <= 3) {
        
        self.loginBtn.backgroundColor = kBackBlue;
        self.loginBtn.userInteractionEnabled = NO;
        
    } else if (sender.text.length > 3 && self.phoneNumber.text.length >= 11) {
        self.loginBtn.backgroundColor = kBlueColor;
        self.loginBtn.userInteractionEnabled = YES;
    }
    
}
    
//点击空白处键盘退出
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        [self.phoneNumber resignFirstResponder];
        [self.codeStr resignFirstResponder];
        
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (_timer1) {
        dispatch_source_cancel(_timer1);
    }
}
    
- (IBAction)didGetCode:(UIButton *)sender {
    self.timeout = 60;//等待时间
    if ([NSString valiMobile:self.phoneNumber.text] ) {
        [self netLoadSecurityCode];
        self.getCodeBtn.backgroundColor = kBackBlue;
        dispatch_queue_t queue  = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer1 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(_timer1, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer1, ^{
            if (self.timeout <= 0) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    self.getCodeBtn.backgroundColor = kBlueColor;
                    [_getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                    self.getCodeBtn.userInteractionEnabled = YES;
                    dispatch_source_cancel(_timer1);
                    
                });
            }else{
                
                NSString *strTime = [NSString stringWithFormat:@"%d",self.timeout];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%@ S",strTime] forState:UIControlStateNormal];
                    self.getCodeBtn.userInteractionEnabled = NO;
                    
                });
                self.timeout--;
            }
        });
        dispatch_resume(_timer1);
    }else {
        [HTShowUtil showMessage:@"手机号码格式不对"];
    }
}
- (IBAction)didLogin:(UIButton *)sender {
    [self netLoadLogin];
}
- (IBAction)didChooseGoodsHolder:(UIButton *)sender {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark --- 网络请求
//请求验证码
- (void)netLoadSecurityCode{
    YDHUD *hud = [YDHUD juhuaHUD];
    [self.view addSubview:hud];
    [hud showAnimated:YES];
    [HTHttpRequestManager requestSecurityCodeWithPhoneNum:self.phoneNumber.text success:^(id  _Nullable responseObject) {
        [hud hideAnimated:YES];
        if (!responseObject) {
            [HTShowUtil showMessage:@"请求验证码错误"];
            return ;
        }
        NSString *data = responseObject[@"data"];
        data = [data substringToIndex:2];
        if ([data isEqualToString:@"03"] ) {
            [HTShowUtil showMessage:@"验证码已发送,请注意查收"];
        }else{
            [HTShowUtil showMessage:@"请求验证码错误"];
        }
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:YES];
        [HTShowUtil showMessage:@"网络错误"];
    }];
}
//请求登陆
- (void)netLoadLogin{
    YDHUD *hud = [YDHUD juhuaHUD];
    [self.view addSubview:hud];
    [hud showAnimated:YES];
    [HTHttpRequestManager requestLoginWithPhoneNum:self.phoneNumber.text withSecurityCode:self.codeStr.text success:^(id  _Nullable responseObject) {
        [hud hideAnimated:YES];
        if (!responseObject) {
            [HTShowUtil showMessage:@"登陆失败"];
            return ;
        }
        NSString *codeString = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if ([codeString isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            //保存当前的token
            [HTMUserDefaultUtil saveUserToken:responseObject[@"token"]];
            [HTMUserDefaultUtil setUserPhone:self.phoneNumber.text];
            [HTMUserDefaultUtil setLogined];
            [HTUtils netLoadNotification];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
             [HTShowUtil showMessage:@"登陆失败"];
        }
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:YES];
    }];
}
#pragma clang diagnostic pop

@end
